define(['jquery', 'knockout', 'eventbus', 'dataservice', 'util'], function ($, ko, eventbus, ds, util) {
	return function () {
		// Observe the question list.
		let questions = ko.observable({});

		// Retrieves the questions and updates the first, last, prev and next urls.
		let retrieveQuestions = function (data) {

			// Update the question list with minified questions.
			questions(data.questions.map(
				// Process the question data for the list view.
				function (question) {
					return util.minifyQuestion(question);
				}
			));
			
			// Add pagination.
			let paginationData = {
				currentUrl: data.currentPageUrl,
				firstUrl: data.firstPageUrl,
				prevUrl: data.previousPageUrl,
				nextUrl: data.nextPageUrl,
				lastUrl: data.lastPageUrl
			}

			// Notify the rest of the system.
			eventbus.publish("questionsLoaded", paginationData);
		}

		// Call an initial retrieval of Questions (page 0).
		ds.getQuestions(retrieveQuestions);

		let getQuestions = function (url) {
			ds.getQuestions(retrieveQuestions, url);
		}

		// Update the selected question and notify about changing the component.
		let navigateToDetails = function (question) {
			localStorage.setItem("selectedQuestionUrl", question.questionUrl);
			eventbus.publish("changeComponentEvent", "question-details");
		}

		return {
			title: 'List Questions',
			questions,
			getQuestions,
			navigateToDetails
		}
	}
});